package com.example.shkjdemo.cameraX

import android.os.Bundle
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.*
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.core.content.ContextCompat
import androidx.databinding.DataBindingUtil
import com.example.shkjdemo.R
import com.example.shkjdemo.databinding.ActivityCameraXBinding
import java.nio.ByteBuffer
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors

typealias LumaListener = (luma: Double) -> Unit
class CameraXActivity : AppCompatActivity() {
    private val TAG = "CameraXActivity"
    lateinit var binding:ActivityCameraXBinding
    private lateinit var cameraExecutor: ExecutorService
    var cameraProvider: ProcessCameraProvider? = null//相机信息
    var preview: Preview? = null//预览对象
    lateinit var previewView: PreviewView
    var cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA//当前相机
    var camera: Camera? = null//相机对象
    private var imageCapture: ImageCapture? = null//拍照用例
    var videoCapture: VideoCapture? = null//录像用例
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this,R.layout.activity_camera_x)
        previewView = binding.previewView

        binding.btnPreview.setOnClickListener {
//            打开预览
            startCameraX()
        }

        binding.btnStopPreview.setOnClickListener {
            cameraProvider?.unbindAll()//先解绑所有用例
        }
    }


    private fun startCameraX(){
            cameraExecutor = Executors.newSingleThreadExecutor()
            val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
            cameraProviderFuture.addListener(Runnable {
                try {
                    cameraProvider = cameraProviderFuture.get()//获取相机信息
                    //预览配置
                    preview = Preview.Builder()
                        .build()
                        .also {
                            it.setSurfaceProvider(previewView.createSurfaceProvider())
                        }

                    imageCapture = ImageCapture.Builder().build()//拍照用例配置

                    val imageAnalyzer = ImageAnalysis.Builder()
                        .build()
                        .also {
                            it.setAnalyzer(cameraExecutor, LuminosityAnalyzer { luma ->
                                Log.d(TAG, "Average luminosity: $luma")
                            })
                        }

                    cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA//使用后置摄像头

                    videoCapture = VideoCapture.Builder()//录像用例配置
//                .setTargetAspectRatio(AspectRatio.RATIO_16_9) //设置高宽比
//                .setTargetRotation(viewFinder.display.rotation)//设置旋转角度
//                .setAudioRecordSource(AudioSource.MIC)//设置音频源麦克风
                        .build()

                    cameraProvider?.unbindAll()//先解绑所有用例
                    camera = cameraProvider?.bindToLifecycle(this, cameraSelector, preview, imageCapture, videoCapture)//绑定用例
                } catch (exc: Exception) {
                    Log.e(TAG, "Use case binding failed", exc)
                }

            }, ContextCompat.getMainExecutor(this))
        }


}
private class LuminosityAnalyzer(private val listener: LumaListener) : ImageAnalysis.Analyzer {

    private fun ByteBuffer.toByteArray(): ByteArray {
        rewind()
        val data = ByteArray(remaining())
        get(data)
        return data
    }

    override fun analyze(image: ImageProxy) {

        val buffer = image.planes[0].buffer
        val data = buffer.toByteArray()
        val pixels = data.map { it.toInt() and 0xFF }
        val luma = pixels.average()

        listener(luma)

        image.close()
    }
}
